<script>
export default {
  name: "RetrieveAccount",
  data() {
    // 验证码校验
    const validatePassword = (rule, confirmPass, callback) => {
      if (confirmPass === null) {
        callback(new Error('请确认密码'))
      } else if (confirmPass !== this.password.password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    };
    const validateEmail = (rule, email, callback) => {
      const reg = /^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/;
      if (email == null) {
        this.pass = false;
        callback(new Error('请输入邮箱地址'))
      } else if (!reg.test(email)) {
        this.pass = false;
        callback(new Error('请输入正确的邮箱地址'))
      }

      this.request.get("/user/verifyUserEmail",{params:{
          userName:this.identity.userName,
          email:this.identity.email
        }}).then(res=>{
        if(res.code!=200){
          this.pass = false;
          callback(new Error(res.msg))
        }else{
          callback();
          this.pass=true;
        }
      })

    };


    const validateCode = (rule, code, callback) => {
      if (code == null) {
        callback(new Error('请输入动态码'))
      } else if (code.length != 6) {
        callback(new Error('动态码为6位'))
      } else {
        this.request.get("/user/verifyEmailCode", {
          params: {
            email: this.identity.email,
            dynamicCode: this.identity.dynamicCode
          }
        }).then(res => {
          if (res.code != 200) {
            callback(new Error('动态码错误或过期，请重新获取'))
          }else{
            callback();
          }
        })
      }
    };

    // const validatePhonenumber = (rule, phonenumber, callback) => {
    //   if (phonenumber == '') {
    //     callback(new Error('请输入手机号码'))
    //   } else if (phonenumber.length != 11) {
    //     callback(new Error('手机号码为11位'))
    //   } else {
    //     this.request.get("/user/isPhonenumberExist", {
    //       params: {
    //         phonenumber: this.user.phonenumber
    //       }
    //     }).then(res => {
    //       if (res.code != 200) {
    //         callback(new Error('手机号码已被注册，请使用其他手机号码'))
    //       }
    //     })
    //   }
    // };

    const validateUserName = (rule, userName, callback) => {
      if (userName === null) {
        callback(new Error('请输入用户名'))
      } else {
        this.request.get("/user/isUsernameExist", {
          params: {
            userName: this.identity.userName
          }
        }).then(res => {
          if (res.code === 200) {
            callback(new Error('用户不存在'))
          }else{
            callback();
          }
        })
      }
    };

    return {
      identity:{
        email: null,
        userName:null,
        dynamicCode:null
      },
      password: {
        password:null,
        confirmPass:null
      },
      disabled: false,
      second: null,
      timer: null,
      activeStep: 0,
      rules1: {
        email: [
          {validator: validateEmail, trigger: 'blur'},
        ],
        userName: [
          {validator: validateUserName, trigger: 'blur'},
        ],
      dynamicCode: [
          {validator:validateCode,trigger:'blur'}
      ]
      },
      rules2:{
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, max: 25, message: '密码至少6位', trigger: 'blur'}
        ],
        confirmPass: [
          {validator: validatePassword, trigger: 'blur'}
        ],
      }
    }
  },
  created() {

  },
  methods: {
    countTime() {
      const TIME_COUNT = 60;
      if (!this.timer) {
        this.second = TIME_COUNT;
        this.disabled = true;
        this.timer = setInterval(() => {
          if (this.second > 0 && this.second <= TIME_COUNT) {
            this.second--;
          } else {
            this.disabled = false;
            clearInterval(this.timer);
            this.timer = null;
          }
        }, 1000);
      }
    },
    getCode() {
      this.$refs.identityRef.validateField('userName',(valid1)=>{
           if(valid1==''){
             this.$refs.identityRef.validateField('email',(valid2)=>{
               if(valid2==''){
                 this.countTime();
                 this.request.get("/user/sendEmailCode", {
                   params: {
                     email: this.identity.email
                   }
                 }).then(res => {
                   if (res.code === 200) {
                     this.$message({
                       message: '动态码已发送到您的邮箱，请及时查看',
                       type: 'success',
                       center: true
                     });
                   } else {
                     this.$message({
                       message: '动态码发送失败，请重新获取',
                       type: 'success',
                       center: true
                     });
                   }
                 })
               }
             })
           }
      })

    },
    next(){
      this.$refs["identityRef"].validate((valid)=>{
        if(valid){
          this.activeStep++;
        }
      })
    },
    resetPassword(){
      this.$refs['passwordRef'].validate((valid)=>{
        if(valid){
          this.request.get("/user/updatePassword",{params:{
            userName:this.identity.userName,
            password:this.password.password
            }}).then(res=>{
              if(res.code===200){
                this.$message({
                  type:"success",
                  message:"密码重置成功",
                  center:true
                })
                this.$router.push("/login")
              }else{
                this.$message({
                  type:"error",
                  message:res.msg,
                  center:true
                })
              }
          })
        }
      })
    }
  },
  computed: {
    content() {
      return this.disabled ? `${this.second}s后重新获取` : '获取动态码';
    }
  }
}

</script>
<template>
  <div style="height: 100vh; display: flex; align-items: center; justify-content: center; background-color:rgb(101, 83, 3);opacity: 0.7">
    <div style="display: flex; background-color: white; width: 50%;height:60%; border-radius: 5px; overflow: hidden">
      <div style="flex: 1">
        <img src="../../assets/retrieveAccount.png" alt="" style="width: 100%;margin-left:30px;margin-top: 40px">
      </div>
      <div style="display: flex; flex:1; align-items: center; justify-content: center">
      <div  style="width:80%">
        <div style="font-size: 20px; font-weight: bold; text-align: center; margin-bottom: 30px">找回密码</div>
        <div v-if="activeStep===0" style="padding-left: 25px">
          <el-form :model="identity" :rules="rules1" ref="identityRef" key="identity">
          <el-form-item prop="userName">
            <el-input v-model="identity.userName" prefix-icon="el-icon-user" size="medium" placeholder="请输入用户名" style="width: 250px"></el-input>
          </el-form-item>
            <el-form-item prop="email">
              <el-input v-model="identity.email" prefix-icon="el-icon-message" size="medium" placeholder="请输入邮箱" style="width: 250px"></el-input>
            </el-form-item>
            <el-form-item prop="dynamicCode">
              <el-input v-model="identity.dynamicCode" prefix-icon="el-icon-chat-dot-square" size="medium" placeholder="请输入动态码" style="width: 150px"></el-input>
              <el-button style="height:35px;margin-left: 10px" :disabled="disabled" @click="getCode">{{content}}</el-button>
            </el-form-item>
            <el-button type="warning" style="width: 150px;text-align: center;margin-left: 50px" @click="next">下一步</el-button>
          </el-form>
        </div>
        <div v-if="activeStep===1" style="padding-left: 25px">
          <el-form :model="password" :rules="rules2" ref="passwordRef" key="password">
            <el-form-item prop="password">
              <el-input v-model="password.password"   prefix-icon="el-icon-lock" size="medium" placeholder="请输入密码" style="width: 250px"></el-input>
            </el-form-item>
            <el-form-item prop="confirmPass">
              <el-input v-model="password.confirmPass"  prefix-icon="el-icon-lock" size="medium" placeholder="请输入新密码" style="width: 250px"></el-input>
            </el-form-item>
            <el-button type="warning" style="width: 100px;text-align: center;margin-left: 15px" @click="activeStep--">返回</el-button>
            <el-button type="warning" style="width: 100px;text-align: center;margin-left: 20px" @click="resetPassword">重置密码</el-button>
          </el-form>
        </div>
        </div>
    </div>

  </div>
  </div>
</template>
<style scoped>

</style>
